<?php

namespace App\Jobs;

use App\Models\Common\Push;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;
use App\Services\Message\MessageService;
use App\Models\Member\Member;

// php artisan make:job FeedsExposure
// php artisan make:job feedDispatch
// php artisan queue:work --queue=FeedDispatch,NotifyUsers,SyncSendMessage
// php artisan queue:work --queue=SyncSendMessage
// 发消息
class SyncSendMessage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $data;

    /**
     * 任务可尝试的次数
     *
     * @var int
     */
    public $tries = 1;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     * $data:
     * @return void
     */
    public function handle()
    {
        //处理
        try {
            if(isset($this->data['push_uuid']))  Push::where('uuid', $this->data['push_uuid'])->update(['state' => 10]);
            MessageService::assignSendMessage(
                $this->data['content'], 
                (int)$this->data['jump_type'],
                $this->data['router'],
                (int)$this->data['send_type'],
                $this->data['send_uuid'],
                $this->data['title'],
                $this->data['type']
            );

            if(isset($this->data['push_uuid']))  Push::where('uuid', $this->data['push_uuid'])->update(['state' => 10]);

        } catch (\Exception $exception) {
            if(isset($this->data['push_uuid']))  Push::where('uuid', $this->data['push_uuid'])->update(['state' => -10]);
            $this->fail($exception);
        }
    }

    /**
     * 
     *  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'migo.laravel_failed_jobs' doesn't exist (SQL: insert into `laravel_failed_jobs` (`connection`, `queue`, `payload`, `exception`, `failed_at`) values (redis,
     **/
    public function fail($exception)
    {
        //
        if(isset($this->data['push_uuid']))  Push::where('uuid', $this->data['push_uuid'])->update(['state' => -10]);
        Log::alert($exception->getMessage());
    }
}


